package com.sky.common;

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.reader.ObjectReader;

import java.lang.reflect.Type;

public class EnumDeserializer implements ObjectReader<Object> {
    @Override
    public Object readObject(JSONReader jsonReader, Type type, Object o, long l) {
        // 获取目标枚举类型
        Class<?> enumClass = (Class<?>) type;

        // 读取JSON中的值
        Object value = jsonReader.readAny();
        if (value == null) {
            return null;
        }

        // 遍历枚举值，匹配code
        for(Object enumConstant : enumClass.getEnumConstants()){
            if(enumConstant instanceof BaseEnum){
                BaseEnum be = (BaseEnum) enumConstant;
                if(be.getCode().equals(Integer.parseInt(value.toString()))){
                    return be;
                }
            }
        }

        throw new IllegalArgumentException("未知的枚举code: " + value);
    }
}
